<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace app\privacyPolicy\controller;

use plugin\saiadmin\basic\BaseController;
use app\privacyPolicy\logic\privacyPolicyLogic;
use app\privacyPolicy\validate\privacyPolicyValidate;
use support\Request;
use support\Response;

/**
 * 隐私政策控制器
 */
class privacyPolicyController extends BaseController
{
    
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->logic = new privacyPolicyLogic();
        $this->validate = new privacyPolicyValidate;
        parent::__construct();
    }

    /**
     * 数据列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        $where = $request->more(['lang_code', 'zh']);
        $query = $this->logic->search($where);
        $data = $this->logic->getList($query);
        return $this->success($data);
    }
    /**
     * 读取数据
     * @param Request $request
     * @param $id
     * @return Response
     */
    public function readDetail(Request $request, $lang_code = 'zh') : Response
    {

        $model = $this->logic->where(['lang_code' => $lang_code])->find();
        if ($model) {
            $data = is_array($model) ? $model : $model->toArray();
            return $this->success($data);
        }
        return $this->success('返回成功');
    }
    /**
     * 保存数据
     * @param Request $request
     * @return Response
     */
    public function save(Request $request) : Response
    {
        $data = $request->post();
        if ($this->validate) {
            if (!$this->validate->scene('save')->check($data)) {
                return $this->fail($this->validate->getError());
            }
        }
        $model = $this->logic->where(['lang_code' => $data['lang_code']])->find();
        if ($model) {
            $result = $this->logic->update($data, [$this->pk => $model['id']]);
        }else{
            $result = $this->logic->save($data);
        }

        if ($result) {
            $this->afterChange('save');
            return $this->success('操作成功');
        } else {
            return $this->fail('操作失败');
        }
    }

}
